package com.pig4cloud.pig.ads.gdt.service.impl;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.ads.gdt.service.GdtAccesstokenService;
import com.pig4cloud.pig.ads.gdt.service.GdtCustomAudiencesFileService;
import com.pig4cloud.pig.ads.gdt.service.GdtCustomAudiencesService;
import com.pig4cloud.pig.ads.pig.mapper.gdt.GdtCustomAudiencesMapper;
import com.pig4cloud.pig.ads.utils.MultipartFileToFile;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.api.entity.ResponseBean;
import com.pig4cloud.pig.api.gdt.dto.GdtCustomAudiencesDto;
import com.pig4cloud.pig.api.gdt.entity.GdtCustomAudiences;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.api.util.MapUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @projectName:pig
 * @description:广点通人群信息
 * @author:Zhihao
 * @createTime:2020/12/4 17:56
 * @version:1.0
 */
@Service
@Slf4j
public class GdtCustomAudiencesServiceImpl extends ServiceImpl<GdtCustomAudiencesMapper, GdtCustomAudiences> implements GdtCustomAudiencesService {

	@Autowired
    GdtAccesstokenService gdtAccesstokenService;
	@Autowired
    GdtCustomAudiencesFileService gdtCustomAudiencesFileService;
	@Autowired
	GdtCustomAudiencesMapper gdtCustomAudiencesMapper;
	/**
	 * 广点通公共域名
	 */
	@Value(value = "${gdt_url}")
	private String gdtUrl;


	/**
	 * 上传到广点通人群包文件
	 *
	 * @param customFile
	 * @param gdtCustomAudiencesDto
	 * @return
	 */
	@Override
	public R uploadCustomAudiencesFile(MultipartFile[] customFile, GdtCustomAudiencesDto gdtCustomAudiencesDto) {

		MultipartFile cfile = customFile[0];

		String originalFileName = cfile.getOriginalFilename();
		if (StringUtils.isEmpty(originalFileName)) {
			return R.failed("未获取到文件名称！");
		}
		String addr = originalFileName.substring(originalFileName.lastIndexOf("."));
		if (StringUtils.isEmpty(addr) || !addr.equals(".zip")) {
			return R.failed("请上传zip格式文件！");
		}
		File file = null;
		try {
			file = MultipartFileToFile.multipartFileToFile(cfile);
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed("文件上传转换异常！请重试！");
		}
		return push(file,gdtCustomAudiencesDto);
	}

	@Override
	public R pushSelfCustomAudience(File cfile, @Valid GdtCustomAudiencesDto gdtCustomAudiencesDto) {
		return push(cfile, gdtCustomAudiencesDto);
	}

    @Override
    public List<GdtCustomAudiences> getAllThirdIdAndNames() {
        return gdtCustomAudiencesMapper.getAllThirdIdAndNames();
    }

    public R push(File cfile, @Valid GdtCustomAudiencesDto gdtCustomAudiencesDto) {


		String accountId = gdtCustomAudiencesDto.getAccountId();

		String name = gdtCustomAudiencesDto.getName();

		String type = gdtCustomAudiencesDto.getType();

		String description = gdtCustomAudiencesDto.getDescription();

		Map<String, String> commonParams = gdtAccesstokenService.fetchAccesstoken(accountId);
		if (commonParams == null || StringUtils.isEmpty(commonParams.get("access_token"))) {
			return R.failed("广点通授权失效!,账号ID: "+ accountId);
		}


		//公共请求参数 包括令牌，时间戳，随机串
		//获得参数
		Map<String, Object> params = new HashMap<>();
		//Integer 推广帐号 id，有操作权限的帐号 id，包括代理商和广告主帐号 id  17209785
		params.put("account_id", accountId);
		params.put("name", name);
		params.put("type", type);
		if (StringUtils.isNotEmpty(description)) {
			params.put("description", description);
		}
		String result = OEHttpUtils.doPost(gdtUrl + "custom_audiences/add" + "?" + MapUtils.queryString(commonParams), params);
		log.info("创建客户人群：\n" + result);

		ResponseBean resBean = JSON.parseObject(result, ResponseBean.class);
		//调用成功,信息入库
		if(resBean != null && "0".equals(resBean.getCode())){
			JSONObject jsonObject = resBean.getData();
			//客户群体Id
			Integer customAudiencesId = jsonObject.getInteger("audience_id");

			return this.createDataSource(customAudiencesId, gdtCustomAudiencesDto, cfile);
		} else {
			return R.failed(resBean == null ? "创建客户人群失败,账号ID: "+ accountId : resBean.getMessage());
		}
	}

	private R createDataSource(Integer customAudiencesId, GdtCustomAudiencesDto gdtCustomAudiencesDto, File cfile) {

		String accountId = gdtCustomAudiencesDto.getAccountId();

		//请求参数
		FileBody file = new FileBody(cfile);

		MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addPart("file", file);
		entityBuilder.addTextBody("account_id", accountId);
		entityBuilder.addTextBody("audience_id", String.valueOf(customAudiencesId));
		//号码包用户 id 类型，[枚举详情]
		//枚举列表：{ GDT_OPENID, HASH_IDFA, HASH_IMEI, HASH_MAC, HASH_MOBILE_PHONE, HASH_QQ, IDFA, IMEI, MAC, MOBILE_QQ_OPENID, QQ, WX_OPENID, WECHAT_OPENID, SALTED_HASH_IMEI, SALTED_HASH_IDFA, OAID, HASH_OAID }
		entityBuilder.addTextBody("user_id_type", gdtCustomAudiencesDto.getUserIdType());

		Map<String, String> commonParams = gdtAccesstokenService.fetchAccesstoken(accountId);

		String resultStr = OEHttpUtils.doFilePost(gdtUrl + "custom_audience_files/add?" + MapUtils.queryString(commonParams), entityBuilder);
		//解析得到data数据
		if (StringUtils.isNotBlank(resultStr)) {
			//数据文件 id
			ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
			//调用成功,信息入库
			if (resBean != null && "0".equals(resBean.getCode())) {
				JSONObject data = resBean.getData();
				if (data != null) {
					Integer fileId = data.getInteger("custom_audience_file_id");
					if (fileId != null) {
//						return R.ok(fileId);
						//删除文件
						FileUtil.del(cfile);
						return R.ok(resBean.getData());
					}
				}
			}
			//中文提示
			return R.failed(resBean.getMessage());
		}
		return R.failed("上传失败！请重试！");
	}

}
